#include "ui_germtab.h"
#include "germtab.h"

GermTab::GermTab(QWidget *parent) :
    QWidget(parent), ui(new Ui::GermTab), imgL(0),
    tcon(new TrainingControl), total(0),
    percent(50), approach(1), size(500), step(100),
    max(1500), hiddenN(10), outputN(1)
{
    ui->setupUi(this);

    ui->appBox->addItem("STATIC");
    ui->appBox->addItem("GROWING");
    ui->appBox->addItem("WINDOWING");

    connect(ui->percentSlider, SIGNAL(sliderMoved(int)), this, SLOT(showPercent(int)));
    connect(ui->appBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setApproach(int)));
    connect(ui->sizeEdit, SIGNAL(textEdited(QString)), this, SLOT(setSize(QString)));
    connect(ui->stepEdit, SIGNAL(textEdited(QString)), this, SLOT(setStep(QString)));
    connect(ui->maxEdit, SIGNAL(textEdited(QString)), this, SLOT(setMaxEpochs(QString)));
    connect(ui->hiddenEdit, SIGNAL(textEdited(QString)), this, SLOT(setHiddenN(QString)));
    connect(ui->outputEdit, SIGNAL(textEdited(QString)), this, SLOT(setOutputN(QString)));
    connect(ui->loadButton, SIGNAL(clicked()), this, SLOT(load()));
    connect(ui->waveletBox, SIGNAL(toggled(bool)), this, SLOT(setWavelet(bool)));
    connect(ui->trainNNButton, SIGNAL(clicked()), this, SLOT(trainNN()));
    connect(ui->runNNButton, SIGNAL(clicked()), this, SLOT(runNN()));
    connect(ui->weightsButton, SIGNAL(clicked()), this, SLOT(loadWeights()));

}

GermTab::~GermTab()
{
    delete ui;
}

void GermTab::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void GermTab::setWavelet(bool checked)
{
    tcon->getGTools()->setWavelet(checked);
}

// When method is 'Growing', a fixed percentage will
// be set and data set will increase with this percentage
// every epoch
void GermTab::showPercent(int percent)
{
    this->percent = percent;
    ui->perLabel->setText(QString::number(percent).append(tr("%")));
}

// A total of three method to retrieve data set
// 'Static', 'Growing', 'Windowing'. Default will
// be 'static' method
void GermTab::setApproach(int approach)
{
    this->approach = approach + 1;

    if(approach == 1)
    {
        ui->splitter_5->setEnabled(true);
        ui->splitter_7->setEnabled(false);
    }
    else if(approach == 2)
    {
        ui->splitter_5->setEnabled(false);
        ui->splitter_7->setEnabled(true);
    }
}

// Size of windowing method. If no selection
// default will be 500
void GermTab::setSize(QString input)
{
    size = toInt(input);

    if(size == 0)
    {
        size = 500;
        ui->sizeEdit->setText("500");
    }
}

// Size of step every time window moves. If no
// selection, default will be 100
void GermTab::setStep(QString input)
{
    step = toInt(input);

    if(step == 0)
    {
        step = 10;
        ui->stepEdit->setText("10");
    }
}

// Max number of epochs before neural network stops.
// Default value will be 1500 epochs
void GermTab::setMaxEpochs(QString input)
{
    max = toInt(input);

    if(max == 0)
    {
        max = 1500;
        ui->maxEdit->setText("1500");
    }
}

// Number of hidden neurons. Default value
// will be 10 hidden neurons
void GermTab::setHiddenN(QString input)
{
    hiddenN = toInt(input);

    if(hiddenN == 0)
    {
        hiddenN = 10;
        ui->hiddenEdit->setText("10");
    }
}

// Numbe of output neurons. Default value
// will be 1 output neurons
void GermTab::setOutputN(QString input)
{
    outputN = toInt(input);

    if(max == 0)
    {
        outputN = 1;
        ui->outputEdit->setText("1");
    }
}

// Convert user input to integer value
// from string input
int GermTab::toInt(const QString &input)
{
    bool ok;
    return input.toInt(&ok, 10);
}

/*
 *  TrainNN button is pressed and start train neural network
 *  will provided / default parameters
 */
void GermTab::trainNN()
{
    QString trFile = QFileDialog::getOpenFileName(this, tr("Open training file for Neural Network"), "/home",
                                                    tr("Training file (*.csv)"));

    // Call training control to start training neural netowrk
    if(tcon->getGTools()->startTraining(trFile, approach, percent, size, step, max, hiddenN))
    {
        ui->trainNNButton->setStatusTip("Neural Network has been trained successfully!");
        ui->runNNButton->setEnabled(true);
    }
    else
    {
        ui->trainNNButton->setStatusTip("No training file available, please train Neural Network first!");
        ui->runNNButton->setEnabled(false);
    }
}

void GermTab::loadWeights()
{
    QString wtFile = QFileDialog::getOpenFileName(this, tr("Open weight file for Neural Network"), "/home",
                                                    tr("Weight file (*.csv)"));

    if(tcon->getGTools()->loadWeights(wtFile, hiddenN, outputN))
    {
        ui->weightsButton->setStatusTip("Weights have load successfully");
        ui->runNNButton->setEnabled(true);
    }
    else
    {
        ui->weightsButton->setStatusTip("No weights available, please try again!");
        ui->runNNButton->setEnabled(false);
    }
}

/*
 *  Run button is pressed
 *  Set program to running mode and load any image to be
 *  identified with trained neural network.
 */
void GermTab::runNN()
{
    // Once an image has been loaded in training control
    // run NN to test it.
    tcon->startRunning();
    // current image in image loader is the image need
    // to be tested by neural network
    loadTCon();
}

/*
 * Load image into 'training control' and start calculation seed texture
 * features using coccurance
 *
*/
void GermTab::load()
{
    if(loadTCon())
    {
        // update number of trained image
        ui->nTrainedImg->setText(QString::number(++total));

        if(!ui->trainNNButton->isEnabled())
            ui->trainNNButton->setEnabled(true);
    }
}

/*
 *  Load up training control, display current image from
 *  image loader.
 *
 */
bool GermTab::loadTCon()
{
    if(imgL)
    {
        QString file = imgL->getCurrFile();

        if(file.length() > 0)
        {
            tcon->addFile(file);
            tcon->show();
            return true;
        }
        else
        {
            this->setStatusTip("Please select an image first.");
        }
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setText("No images have been loaded.");
        msgBox.exec();
    }
    return false;
}

void GermTab::addLoader(ImageLoader *imageLoader)
{    
    if(imageLoader)
    {
        ui->gridLayout->addWidget(imageLoader, 0, 0);
        imgL = imageLoader;
    }
}

void GermTab::showContent()
{
    if(imgL)
        ui->gridLayout->addWidget(imgL, 0, 0);
}
